import React, { useState, useEffect } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import './index.css';
// 定义订单类型
type Order = {
  id: number;
  status: '待付款' | '已完成';
  amount: number;
  createdAt: string;
  isRecommended: boolean;
};
// 模拟订单数据
const mockOrders: Order[] = Array.from({ length: 50 }, (_, index) => ({
  id: index + 1,
  status: ['待付款', '已完成'][Math.floor(Math.random() * 2)],
  amount: Math.floor(Math.random() * 1000),
  createdAt: new Date().toISOString(),
  isRecommended: false,
}));
 
 const ExportButton = () => {
    // 当前选中的 tab
  const [activeTab, setActiveTab] = useState<'全部' | '待付款' | '已完成'>('全部');
  // 存储当前过滤后的订单
  const [orders, setOrders] = useState<Order[]>([]);
  // 存储选中的订单 ID
  const [selectedOrderIds, setSelectedOrderIds] = useState<number[]>([]);
  // 当前加载的页数
  const [page, setPage] = useState(1);
  // 每页显示的订单数量
  const recordsPerPage = 15;
  // 是否还有更多数据
  const [hasMore, setHasMore] = useState(true);
  useEffect(() => {
    // 初始化加载数据
    const loadInitialData = () => {
      const startIndex = 0;
      const endIndex = startIndex + recordsPerPage;
      const initialOrders = mockOrders.filter((order) => {
        if (activeTab === '全部') return true;
        return order.status === activeTab;
      }).slice(startIndex, endIndex);
      setOrders(initialOrders);
      setPage(1);
      setHasMore(mockOrders.length > endIndex);
    };
    loadInitialData();
  }, [activeTab]);
  // 加载更多数据
  
  const loadMore = () => {
// 3秒后加载下一页数据
    setTimeout(() => {
       const startIndex = page * recordsPerPage;
    const endIndex = startIndex + recordsPerPage;
    const newOrders = mockOrders.filter((order) => {
      if (activeTab === '全部') return true;
      return order.status === activeTab;
    }).slice(startIndex, endIndex);
    if (newOrders.length > 0) {
      setOrders((prevOrders) => [...prevOrders, ...newOrders]);
      setPage((prevPage) => prevPage + 1);
    } else {
      setHasMore(false);
    }
    },1000)



   
  };
  // 处理单个订单的选择
  const handleSingleSelect = (orderId: number, isChecked: boolean) => {
    if (isChecked) {
      setSelectedOrderIds([...selectedOrderIds, orderId]);
    } else {
      setSelectedOrderIds(selectedOrderIds.filter((id) => id!== orderId));
    }
  };
  // 处理全选操作
  const handleSelectAll = (isChecked: boolean) => {
    if (isChecked) {
      setSelectedOrderIds(orders.map((order) => order.id));
    } else {
      setSelectedOrderIds([]);
    }
  };
  // 批量设置为推荐
  const handleBatchRecommend = () => {
    const newOrders = orders.map((order) => {
      if (selectedOrderIds.includes(order.id)) {
        return { ...order, isRecommended: true };
      }
      return order;
    });
    setOrders(newOrders);
    setSelectedOrderIds([]);
  };
  // 单个设置为推荐
  const handleSingleRecommend = (orderId: number) => {
    const newOrders = orders.map((order) => {
      if (order.id === orderId) {
        return { ...order, isRecommended: true };
      }
      return order;
    });
    setOrders(newOrders);
  };
 
   return (
       <div className='tabss' style={{ padding: '20px' }}>
      {/* tabs 切换栏 */}
      <div style={{ marginBottom: '20px' }}>
        <button
          style={activeTab === '全部' ? { backgroundColor: '#007bff', color: 'white' } : {}}
          onClick={() => setActiveTab('全部')}
        >
          全部
        </button>
        <button
          style={activeTab === '待付款' ? { backgroundColor: '#007bff', color: 'white' } : {}}
          onClick={() => setActiveTab('待付款')}
        >
          待付款
        </button>
        <button
          style={activeTab === '已完成' ? { backgroundColor: '#007bff', color: 'white' } : {}}
          onClick={() => setActiveTab('已完成')}
        >
          已完成
        </button>
      </div>
      {/* 全选和批量推荐按钮 */}
      <div style={{ marginBottom: '10px' }}>
        <input
          type="checkbox"
          checked={selectedOrderIds.length === orders.length}
          onChange={(e) => handleSelectAll(e.target.checked)}
        />
        <label>全选</label>
        <button onClick={handleBatchRecommend} disabled={selectedOrderIds.length === 0}>
          批量设置为推荐
        </button>
      </div>
      {/* 订单列表 */}
      <InfiniteScroll
        dataLength={orders.length}
        next={loadMore}
        hasMore={hasMore}
        loader={
          <div style={{ textAlign: 'center', padding: '20px' }}>
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        }
      >
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>选择</th>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>订单 ID</th>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>订单状态</th>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>订单金额</th>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>创建时间</th>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>是否推荐</th>
              <th style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>操作</th>
            </tr>
          </thead>
          <tbody>
            {orders.map((order) => (
              <tr key={order.id}>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>
                  <input
                    type="checkbox"
                    checked={selectedOrderIds.includes(order.id)}
                    onChange={(e) => handleSingleSelect(order.id, e.target.checked)}
                  />
                </td>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>{order.id}</td>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>{order.status}</td>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>{order.amount}</td>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>{order.createdAt}</td>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>
                  {order.isRecommended ? '是' : '否'}
                </td>
                <td style={{ border: '1px solid #ccc', padding: '8px', textAlign: 'left' }}>
                  <button onClick={() => handleSingleRecommend(order.id)}>设置为推荐</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </InfiniteScroll>
      <style>{`
        .loading-spinner {
          border: 4px solid rgba(0, 0, 0, 0.1);
          border-left-color: #007bff;
          border-radius: 50%;
          width: 24px;
          height: 24px;
          animation: spin 1s linear infinite;
          margin: 0 auto 10px;
        }
        @keyframes spin {
          to {
            transform: rotate(360deg);
          }
        }
      `}</style>
    </div>
   )
 }
 
 export default ExportButton